var config = require('./config');

App({
  onLaunch: function () {
    console.info('loading app...');
    wx.showLoading({
      title: '正在获取信息',
      mask: true
    });
    var that = this;
    wx.request({
      url: config.host + '/school/province',
      success: function (res) {
        that.globalData.province = res.data;
        wx.hideLoading();
      }
    })
    wx.showLoading({
      title: '登录中',
      mask: true
    });
  },

  //检测是否登录
  checkLogin: function (cb) {
    console.info('checking login...');
    var skey = wx.getStorageSync('skey');
    if (skey) {
      console.log('Getting userInfo');
      this.getUserInfo(cb);
    }
    else {
      console.log('login');
      this.login(cb);
    }
  },

  //登录
  //step1，调用wx.login获取code
  //step2，发送code到腾讯云，并且返回第三方skey，存储到本地
  //step3，获取用户信息
  login: function (cb) {
    console.info('login...');
    var that = this;
    wx.login({
      success: function (res) {
        // 登录请求
        console.log(res);
        wx.request({
          url: config.host + '/login',
          data: {
            code: res.code
          },
          success: function (res) {
            console.log(res);
            var skey = res.data.skey;
            console.info('already login, skey is', skey);
            //如果获取不到skey，则重试
            if (!skey) {
              that.login(cb);
              return;
            }
            wx.setStorageSync('skey', skey);
            that.getUserInfo(cb);
          }
        })
      },
    });
  },

  //获取用户信息
  //对于未登录用户，重新登录
  //对于未注册用户，注册新用户
  
  /*路人要在结束时删除登陆记录*/

  //对于已注册用户，全局写入用户信息
  getUserInfo: function (cb) {
    var that = this;
    this.request({
      url: '/user',
      success: function (res) {
        console.log('getRes: ');
        console.log(res);
        // 未登录
        if (res.statusCode === 401) {
          console.log('401');
          that.login(cb);
        }
        else {
          // 未注册用户
          if (res.statusCode === 400) {
            wx.reLaunch({
              url: '/pages/register/register-step1/register-step1'
            });
            console.log('400');
            //that.registerUser(cb);
          }
          else {
            console.log('Got userInfo success!');
            that.globalData.userInfo = {
              open_id:res.data.open_id,
              user_group_id: res.data.user_group_id,
              name: res.data.name,
              province:res.data.province,
              city:res.data.city,
              school_name: res.data.school_name,
              sch_id: res.data.sch_id,
              habit_1: res.data.habit_1,
              habit_2: res.data.habit_2,
              habit_3: res.data.habit_3,
              habit_4: res.data.habit_4,
              habit_5: res.data.habit_5,
              habit_6: res.data.habit_6,
              avatar: res.data.avatar
            }
            wx.hideLoading();
            cb();
          }
        }
      },
      fail:function(res){
        console.log(res);
      }
    });
  },

  //注册用户
  //在User表中添加记录
  //授权失败写入默认用户信息，否则写入通过wx.getUserInfo获取的用户信息
  registerUser: function (cb) {
    console.log(this.globalData);
    var that = this;
    wx.getUserInfo({
      success: function (res) {
        console.log('userinfo');
        console.log(res);
        that.globalData.userInfo.name = res.userInfo.nickName;
        that.globalData.userInfo.avatar = res.userInfo.avatarUrl;
        that.request({
          url: '/user',
          method: 'POST',
          data: that.globalData.userInfo,
          success: function (res) {
            cb();
            console.log(res);
            wx.hideLoading();
          },
          fail: function () {
            var th=that;
            wx.showModal({
              title: '注册失败',
              content: '是否重试？',
              confirmText: '是',
              cancelText: '否',
              success:function(res){
                if(res.confirm){
                  th.register(cb);
                }
                else if(res.cancel){
                  //跳转index   ！未测试
                  wx.navigateBack({
                    delta: 2
                  });
                }
              }
            });
            console.log('register failed');
          }
        });
      },
      //授权失败，用默认值注册
      fail: function (res) {
        console.log('authorized failed');
        console.log(res);
        wx.showLoading({
          title: '正在使用默认参数重试',
        })
        that.request({
          url: '/user',
          method: 'POST',
          data: that.globalData.userInfo,
          success: function () {
            wx.hideLoading();
            cb();
            wx.hideLoading();
          },
          fail: function(){
            var th=that;
            console.log('register failed with default value');
            wx.hideLoading();
            wx.showModal({
              title: '使用默认值注册失败',
              content: '是否重试？',
              confirmText: '是',
              cancelText: '否',
              success: function (res) {
                if (res.confirm) {
                  th.register(cb);
                }
                else if (res.cancel) {
                  //跳转index   ！未测试
                  wx.navigateBack({
                    delta: 2
                  });
                }
              }
            })
          }
        });
      }
    })
  },

  //封装wx.request，自动添加host以及API版本号
  request: function (obj) {
    var skey = wx.getStorageSync('skey'); 
    console.log(skey);
    obj.url = config.host + obj.url;
    obj.header = {
      skey: skey,
      version: config.apiVersion
    };
    console.log(obj);
    return wx.request(obj);
  },

  //请求市列表
  reqCity:function(obj){
    obj.url = config.host + '/school/city';
    return wx.request(obj);
  },

  //请求学校列表
  reqSch:function(obj){
    obj.url=config.host+'/school'
    console.log(obj);
    return wx.request(obj);
  },

  //全局数据维护
  globalData: {
    //默认值
    userInfo: {
      open_id: null,
      user_group_id: 0,
      name: '未注册用户',
      province:null,
      city:null,
      school_name:null,
      sch_id: null,
      habit_1: null,
      habit_2: null,
      habit_3: null,
      habit_4: null,
      habit_5: null,
      habit_6: null,
      avatar: null,
      corFollowing:[]
    },
    province:[],
    hobby:['体育','文艺','展会','市场','讲座','户外','公益','娱乐','比赛','表演','科技','美食'],
    actStyle:[],
  }
})
